﻿namespace PillBox.Client.Framework
{
    using System.Collections.Generic;
    using System.Windows;

    public static class ApplicationFrame
    {
        public static DependencyProperty ModelProperty =
            DependencyProperty.RegisterAttached(
                "Model",
                typeof(object),
                typeof(ApplicationFrame),
                new PropertyMetadata(ModelChanged)
                );

        public static void SetModel(DependencyObject d, object value)
        {
            d.SetValue(ModelProperty, value);
        }

        public static object GetModel(DependencyObject d)
        {
            return d.GetValue(ModelProperty);
        }

        public static void ModelChanged(object sender, DependencyPropertyChangedEventArgs args)
        {
            if (args.NewValue == null || args.NewValue == args.OldValue)
                return;

            new DoNavigation(args.NewValue);
        }

        private class DoNavigation
        {
            private object _viewModel;

            public DoNavigation(object viewModel)
            {
                this._viewModel = viewModel;

                ResultEnumerator.Begin(this.Enumerate());
            }

            private IEnumerable<IResult> Enumerate()
            {
                yield return new DeActivateCurrentViewResult();
                yield return new NavigateResult(this._viewModel);
            }
        }
    }
}